import binascii
import json
from utils import extract_images, get_real_time, extract_time
from utils.database import Model
from utils.save import Save


class QQ(Model, Save):
    table = "news_qq"

    def add(self, item):
        self.do_insert({
            "title": item["title"].strip(),
            "link": item["link"].strip(),
            "link_crc32": binascii.crc32(item["link"].encode()),
            "preview_images": json.dumps(item["images"]),
            "sort": int(item["sort"]),
            "author": item["author"],
            "author_url": item["author_url"],
            "publish_time": get_real_time(item["publish_time"]),
            "create_time": item["update_time"],
            "update_time": item["update_time"]
        })

    def update(self, id, item):
        params = {
            "update_time": item["update_time"],
            "preview_images": json.dumps(item["images"]),
            "sort": int(item["sort"]),
        }

        self.do_update(params, {"id": id})

    def get_tops(self, num):
        sql = "select * from $table order by update_time desc, `sort` asc limit ?"
        params = (num,)

        result = self.query_all(sql, params)

        extract_images(result)

        extract_time(result)

        return result
